﻿using Entity;
using ServiceCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Customer.Bussiness_Service
{
    public interface Islot_template_service
    {
        /// <summary>
        /// 保存模板设置
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel save_template(slot_template Params);
        /// <summary>
        /// 获取模板详情
        /// </summary>
        /// <param name="template_id"></param>
        /// <param name="box_no"></param>
        /// <param name="box_capacity"></param>
        /// <returns></returns>
        ResultObjModel get_template(string template_id, int box_no = 0, int box_capacity = 100); 
        /// <summary>
        ///  获取模板列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel get_template_list(get_template_list_params query);
        /// <summary>
        /// 删除模板消息
        /// </summary>
        /// <param name="template_id"></param>
        /// <returns></returns>
        ResultModel del_template(string template_id);
    }
    public class slot_template_service : Islot_template_service
    {
        private readonly IToole_DI _tool;

        public slot_template_service(IToole_DI Tool)
        {
            _tool = Tool;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ResultObjModel save_template(slot_template Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (Params == null)
                {
                    result.code = 1;
                    result.msg = "未传入任何参数";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(Params.template_name))
                {
                    result.code = 1;
                    result.msg = "模板名称不能为空";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(Params.slot_group))
                {
                    result.code = 1;
                    result.msg = "请设置货道内容";
                    return result;
                }
                List<SlotGroup> slot_list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<SlotGroup>>(Params.slot_group);
                if (slot_list == null)
                {
                    result.code = 1;
                    result.msg = "货道内容不能为空";
                    return result;
                }
                if (slot_list.Where(s => !s.row_index.HasValue).Any())
                {
                    result.code = 1;
                    result.msg = "存在未设置货道层级的数据";
                    return result;
                }
                if (slot_list.Where(s => s.column_list.Where(p => !p.column_index.HasValue).Any()).Any())
                {
                    result.code = 1;
                    result.msg = "存在未设置货道列数的数据";
                    return result;
                }
                //解析出当前设置的机器类型是什么
                if (string.IsNullOrWhiteSpace(Params.mch_kid_type_id))
                {
                    result.code = 1;
                    result.msg = "请选择当前模板的使用机器类型";
                    return result;
                }
                var kid_type_model = Params.mch_kid_type_id.Split("_");
                Params.Mch_Type = (Mch_Type)Convert.ToInt32(kid_type_model[0]);
                Params.mch_kid_type = kid_type_model[2].ToString(); 
                if (string.IsNullOrWhiteSpace(Params.template_id))
                {
                    Params.template_id = "";
                }
                var check_model = _tool.di_db.GetList<slot_template>("select * from slot_template where template_id<>@template_id and template_name=@template_name", Params).FirstOrDefault();
                if(check_model != null)
                {
                    result.code = 1;
                    result.msg = "模板名称已存在";
                    return result;
                }
                 
                //判断当前是添加还是修改
                if (string.IsNullOrWhiteSpace(Params.template_id))
                {
                    int? maxcount = _tool.di_db.GetList<int?>("select max(template_No) from slot_template", null).FirstOrDefault();
                    if (!maxcount.HasValue)
                    {
                        maxcount = 0;
                    }
                    Params.template_id = _tool.di_getid.IGet_SnowFlake_Id;
                    Params.template_No = maxcount.Value + 1;
                    //当前添加，直接添加一个数据 
                    Params.show_No = Params.template_No.ToString().PadLeft(Params.template_No.ToString().Length > 3 ? Params.template_No.ToString().Length : 3, '0');
                    Params.addtime = DateTime.Now;
                    Params.adduser = _tool.di_user.USER.uid;
                    Params.adduser_name = _tool.di_user.USER.u_name;
                    Params.slot_group = Newtonsoft.Json.JsonConvert.SerializeObject(slot_list);
                    Params.Isdelete = false;
                    //保存数据
                    int add_rows = _tool.di_db.Add(Params);
                    if (add_rows > 0)
                    {
                        result.code = 0;
                        result.msg = "保存成功";
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "保存失败";
                    }
                    return result;
                }
                else
                {
                    //当前修改 
                    var update_item = _tool.di_db.GetList<slot_template>("select * from slot_template where template_id=@template_id", new { Params.template_id }).FirstOrDefault();
                    if (update_item == null)
                    {
                        result.code = 1;
                        result.msg = "待修改数据不存在";
                        return result;
                    }
                    Params.slot_group = Newtonsoft.Json.JsonConvert.SerializeObject(slot_list);
                    int updaterow = _tool.di_db.Update<slot_template>(new string[] { "CanUse", "Mch_Type", "template_name", "slot_group", "mch_kid_type", "mch_kid_type_id" }, new string[] { "template_id=@template_id" }, Params);
                    if (updaterow > 0)
                    {
                        result.code = 0;
                        result.msg = "修改成功";
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "修改失败";
                    }
                    return result;
                }
            }); 
        }

    
        /// <summary>
        /// 获取货道模板
        /// </summary>
        /// <param name="template_id">模板ID</param>
        /// <param name="box_no">i请求柜体 不传则为主柜</param>
        /// <param name="box_capacity">单柜容量</param>
        /// <returns></returns>
        public ResultObjModel get_template(string template_id, int box_no = 0, int box_capacity = 100)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(template_id))
                {
                    result.code = 1;
                    result.msg = "必须入参模板ID";
                    return result;
                }
                slot_template tempinfo = _tool.di_db.GetList<slot_template>("select top 1 * from slot_template where template_id=@template_id and CanUse='true' and Isdelete=@Isdelete", new { template_id, Isdelete = false }).FirstOrDefault();
                if (tempinfo == null)
                {
                    result.code = 1;
                    result.msg = "未能找到模板数据";
                    return result;
                }
                //获取当前货道设置
                List<SlotGroup> slot_list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<SlotGroup>>(tempinfo.slot_group);
                //定义模板容器
                List<slotItem> slot_set = new List<slotItem>();
                //标记公式  实际货道号 应该等于  ((当前行数-1）* 单行最大设置值10) + 当前列数  + 请求柜体 * 单柜数量
                foreach (var itemRow in slot_list)
                {
                    int rowsIndex = itemRow.row_index.Value;
                    var column_Array = itemRow.column_list.Where(s => s.count.HasValue).ToList();
                    foreach (var itemColumn in column_Array)
                    {
                        slot_set.Add(new slotItem()
                        {
                            index = (10 * (rowsIndex - 1)) + itemColumn.column_index.Value + box_no * box_capacity,
                            maxcount = itemColumn.count.Value,
                            height = itemRow.hight
                        });
                    }
                }
                result.code = 0;
                result.msg = "success";
                result.data = new
                {
                    original_data = slot_list,
                    slot_set
                };
                return result;
            });
        }

        /// <summary>
        /// 获取货道列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel get_template_list(get_template_list_params query)
        {
            return CoreStartDo.ResultAction<ResultListModel>(result =>
            {
                string sql = "select * from slot_template";
                string where = " where CanUse='true' and Isdelete='false'";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                if (query.mch_type.HasValue)
                {
                    where += " and Mch_Type=@Mch_Type";
                    query_dy.Mch_Type = query.mch_type;
                } 
                if (!string.IsNullOrWhiteSpace(query.mch_kid_type_id))
                {
                    where += " and mch_kid_type_id=@mch_kid_type_id";
                    query_dy.mch_kid_type_id = query.mch_kid_type_id;
                } 
                if (query.search_type.HasValue && !string.IsNullOrWhiteSpace(query.search_key))
                {
                    switch (query.search_type.Value)
                    {
                        case template_search_type.编号:
                            where += " and show_No like @search_key";
                            query_dy.search_key = $"%{query.search_key}%";
                            break;
                        case template_search_type.模板名称:
                            where += " and template_name like @search_key";
                            query_dy.search_key = $"%{query.search_key}%";
                            break;
                    }
                }
                ResultListModel<slot_template> result_pagelist = _tool.di_db.GetPageList<slot_template>(sql, where, "addtime", query_dy, query.IsPage, query.page, query.pagesize);
                result.code = 0;
                result.msg = "success";
                result.rows = result_pagelist.rows;
                result.total = result_pagelist.total;
                result.current = query.page.Value;
                return result;
            });
        }

        /// <summary>
        ///  删除模板消息
        /// </summary>
        /// <param name="template_id"></param>
        /// <returns></returns>
        public ResultModel del_template(string template_id)
        {
            return CoreStartDo.ResultAction<ResultModel>(result =>
            {
                if (string.IsNullOrWhiteSpace(template_id))
                {
                    result.code = 1;
                    result.msg = "模板id必须入参";
                    return result;
                }
                var slot_temp = _tool.di_db.GetModel<slot_template>(new string[] { "template_id=@template_id" }, new { template_id });
                if (slot_temp == null)
                {
                    result.code = 1;
                    result.msg = "货道模板不存在";
                    return result;
                }
                //int del = _tool.di_db.do_Execute("delete from slot_template where template_id=@template_id", new { template_id });
                int del = _tool.di_db.do_Execute("update slot_template set Isdelete=@Isdelete where template_id=@template_id", new { template_id, Isdelete = true });
                if (del > 0)
                {
                    result.code = 0;
                    result.msg = "删除成功";
                }
                else {
                    result.code = 1;
                    result.msg = "删除失败";
                }
                return result;
            });
        }
    }
}
